package com.common.config.user;


import com.common.utils.CookieUtil;
import com.common.utils.JwtUtils;
import com.common.utils.MD5Utils;
import com.generator.LoginException;
import com.generator.NoTokenException;
import com.vo.UserVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义用户参数
 *
 * @author yangzhan
 * HandlerMethodArgumentResolver 用于获取当前登录用户
 * 该类是用于用户校验，在用户controller入参前进行一次校验
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        return clazz == UserVO.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        //获取浏览器的cookie值
//        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        String ticket = "" ;
        // 获取前端浏览器的cookie的token值
        String token = CookieUtil.getCookieValue(request, "userToken");
//        System.out.println("token = " + token);

        Claims claims = JwtUtils.checkToken(token);
        if (claims == null) {
            throw new LoginException("");
        }
        //获取存在token里的登录用户名
        String username = (String) claims.get("username");
        //
        Object red = redisTemplate.opsForValue().get("user:" + username);
//        System.out.println("========================" + username);
        //判断用户是否存在redis
        if (red == null) {
            throw new LoginException("请重新登录!!!");
        }
        String tokenRedis = (String) red;
        //判断浏览器的token是否与redis的token相同
        if (!MD5Utils.md5(token).equals(MD5Utils.md5(tokenRedis))) {
            throw new NoTokenException("你已被强制下线");
        }
//        System.out.println("========================" + tokenRedis);

        //判断是否为空
//        if (StringUtils.isEmpty(ticket)) {
//            return null;
//        }
        //返回用户信息到controller方法前面
        return UserByCookie.getUserByCookie(tokenRedis, ticket, request, response, redisTemplate);
    }
}